<template>
  <!--  面包屑导航-->
  <el-breadcrumb separator=">">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>商品管理</el-breadcrumb-item>
    <el-breadcrumb-item>添加商品</el-breadcrumb-item>
  </el-breadcrumb>
  <!--  卡片区域-->
  <el-card>
    <!--    消息提示区域-->
    <el-alert title="添加商品信息" type="info" center show-icon :closable="false"> </el-alert>
    <!--添加商品分步导航条-->
    <el-steps :space="200" :active="activeIndex-1+''" align-center finish-status="success">
      <el-step title="基本信息"></el-step>
      <el-step title="商品参数"></el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="商品图片"></el-step>
      <el-step title="商品内容"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>
    <!--    tab标签页-->
    <el-form
        ref="addGoodsFormRef"
        :model="addGoodsForm"
        :rules="addGoodsRules"
        label-width="120px"
        class="demo-ruleForm"
    >
      <el-tabs @tab-click="tabClicked" :before-leave="beforeTabLeave" v-model="activeIndex" :tab-position="tabPosition" class="demo-tabs">
        <el-tab-pane label="基本信息" name="1">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="addGoodsForm.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price">
            <el-input v-model="addGoodsForm.goods_price"></el-input>
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight">
            <el-input v-model="addGoodsForm.goods_weight"></el-input>
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_number">
            <el-input v-model="addGoodsForm.goods_number"></el-input>
          </el-form-item>
          <el-form-item label="商品分类" prop="goods_cat">
            <el-cascader
                v-model="addGoodsForm.goods_cat"
                :options="casCarderOptions"
                :props="casCarderProps"
                @change="casCarderHandleChange"
            ></el-cascader>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品参数" name="2">
          <el-form-item v-for="item in manyTabCategoriesParams" :key="item.attr_id" :label="item.attr_name">
            <el-checkbox-group @change="changeCheckBox" v-model="item.attr_vals">
              <el-checkbox border v-for="(para,i) in item.attr_vals" :key="i" :label="para" />
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品属性" name="3">
          <el-form-item v-for="item in onlyTabCategoriesParams" :key="item.attr_id" :label="item.attr_name">
            <el-input v-model="item.attr_vals"></el-input>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品图片" name="4">
          <el-form-item>
            <el-upload
                class="upload-demo"
                :action="actionURL"
                :headers="uploadHeader"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                list-type="picture"
                multiple
            >
              <el-button type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品内容" name="5">
          <el-form-item label="商品描述">
            <el-input v-model="addGoodsForm.goods_introduce" type="textarea"></el-input>
            <el-button type="primary" @click="addGoods">添加商品</el-button>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <!--    预览图片的对话框-->
    <el-dialog title="图片预览" v-model="previewDialogVisible" width="50%">
      <img :src="previewURL" alt="图片预览" style="width: 50%; height: auto">
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import {computed, reactive, Ref, ref} from "vue";
import {ElForm, ElMessage} from "element-plus";
import {AddGoods, GetCategoriesList, GetCategoriesParamsList} from "@/api";
import {useRouter} from "vue-router";
import _ from 'lodash'
import {ITabCategoriesParams} from '@/util/interface'
const router = useRouter()
// tab标签页方向
const tabPosition = ref('left')
// 分布导航条激活页
const activeIndex = ref(0)
// 添加商品信息表单对象
const addGoodsForm = reactive({
  goods_name: '',
  goods_price: 0,
  goods_number: 0,
  goods_weight: 0,
  goods_cat: [],
  attrs: [],
  pics: [] as any[],
  goods_introduce: ''
})
// 添加商品信息验证规则
const addGoodsRules = reactive({
  goods_name: [
    {required: true, message: '请输入商品名称', trigger: 'blur'}
  ],
  goods_price: [
    {required: true, message: '请输入商品价格', trigger: 'blur'}
  ],
  goods_number: [
    {required: true, message: '请输入商品数量', trigger: 'blur'}
  ],
  goods_weight: [
    {required: true, message: '请输入商品重量', trigger: 'blur'}
  ],
  goods_cat: [
    {required: true, message: '请选择商品分类', trigger: 'blur'}
  ]
})
// 添加商品信息表单对象的引用
const addGoodsFormRef = ref<InstanceType<typeof ElForm> | null>(null)
// 商品分类级联选择器数据对象
const casCarderOptions = ref([])
// 商品分类级联选择器配置选项
const casCarderProps = reactive({
  expandTrigger: 'hover',
  value: 'cat_id',
  label: 'cat_name',
  children: 'children',
})
//获取所有的商品分类数据
const getOneTwoCategories = async ()=>{
  const {data: res} = await GetCategoriesList()
  console.log(res)
  if(res.meta.status !== 200) {return ElMessage.error(res.meta.msg)}
  casCarderOptions.value = res.data
  ElMessage.success(res.meta.msg)
}
getOneTwoCategories()
//级联选择器change事件
const casCarderHandleChange =()=> {
  // console.log(addGoodsForm.goods_cat)
  if(addGoodsForm.goods_cat.length !== 3){
    addGoodsForm.goods_cat = []
  }
}
// 切换tab标签页
const beforeTabLeave = (activeName: string, oldActiveName: string)=>{
  // console.log(activeName, oldActiveName)
  if(oldActiveName === '1' && addGoodsForm.goods_cat.length !== 3){
    ElMessage.error('请选择商品分类')
    return false
  }
}
// 获取分类id
const cateId = computed(()=>{
  if(addGoodsForm.goods_cat.length === 3){

    return addGoodsForm.goods_cat[2]
  }
  return null
})
// 动态参数列表
const manyTabCategoriesParams = ref<ITabCategoriesParams[]>([])
// 静态属性
const onlyTabCategoriesParams = ref<ITabCategoriesParams[]>([])
// 点击标签页
const tabClicked = async ()=>{
  if(activeIndex.value === 2){
    // 获取分类数据
    // console.log(cateId.value)
    const {data: res} = await GetCategoriesParamsList(cateId.value, {sel: 'many'})
    console.log(res)
    if(res.meta.status !== 200){ return ElMessage.error('获取动态参数列表失败')}
    res.data.forEach((item: any) => {
      item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(',')
    })
    console.log('动态参数')
    console.log(res.data)
    manyTabCategoriesParams.value = res.data
  }else if(activeIndex.value === 3){
    const {data: res} = await GetCategoriesParamsList(cateId.value, {sel: 'only'})
    if(res.meta.status !== 200){ return ElMessage.error('获取静态属性失败')}
    console.log('静态属性')
    console.log(res.data)
    onlyTabCategoriesParams.value = res.data

  }
}
// 多选框选中change事件
const changeCheckBox = ()=>{
  console.log(addGoodsForm.attrs)
}
// 图片上传
const actionURL = 'https://lianghj.top:8888/api/private/v1/upload'
const uploadHeader = {
  Authorization : window.sessionStorage.getItem('token')
}
//预览图片的地址url
const previewURL = ref('')
// 预览图片对话框的显示对象
const previewDialogVisible = ref(false)
// 预览图片
const handlePreview = (file: any)=>{
  console.log('点击图片')
  console.log(file)
  previewURL.value = file.response.data.url
  previewDialogVisible.value = true
}
// 移除图片
const handleRemove = (file: any)=>{
  const findPath = file.response.data.tmp_path
  const findIndex = addGoodsForm.pics.findIndex(item => item.pic === findPath)
  console.log('要删除的图片为：' + findPath)
  console.log('要删除的图片索引为：' + findIndex)
  addGoodsForm.pics.splice(findIndex, 1)
  console.log(addGoodsForm.pics)
}
// 上传成功
const handleSuccess = (response: any)=>{
  const picInfo = {pic: response.data.tmp_path}
  addGoodsForm.pics.push(picInfo)
  console.log(addGoodsForm.pics)
}
// 添加商品
const addGoods = ()=>{

  addGoodsFormRef.value?.validate(async (valid?: boolean)=>{
    if(!valid){return ElMessage.error('商品信息有误，请返回修改！')}
    // const form = _.cloneDeep(addGoodsForm)
    const form = JSON.parse(JSON.stringify(addGoodsForm))
    form.goods_cat = form.goods_cat.join(',')
    // 处理动态参数
    manyTabCategoriesParams.value.forEach((item: any) => {
      form.attrs.push({attr_id: item.attr_id, attr_value: item.attr_vals.join(',')})
    })
    // 处理动态参数
    onlyTabCategoriesParams.value.forEach((item: any) => {
      form.attrs.push({attr_id: item.attr_id, attr_value: item.attr_vals})
    })
    console.log('开始添加商品')
    const {data: res} = await AddGoods(form)
    console.log('添加商品的返回为：')
    console.log(res)
    if(res.meta.status !== 201) { return ElMessage.error('添加商品失败')}
    await router.push('/goods')
  })
}

</script>

<style lang="less" scoped>
.el-button{
  margin-top: 15px;
}
</style>